from flask import Blueprint, jsonify
from flask_restful import Api, Resource, fields, reqparse, marshal
from ext import cache

from ext.arg_check import CheckBookArgs
from ext.reusability import base_result
from ext.marshal_field import book_detail_info_marshal_with, book_simple_info_marshal_with

# 引入模型
from apps.models.book import Book, BookTag, Chapter

# 创建蓝图
book_bp = Blueprint('book', __name__, url_prefix='/api/book')
api = Api(book_bp)


# 书籍信息
class GetBookInfo(Resource):

    book_info_parser = reqparse.RequestParser()
    book_info_parser.add_argument('book_id', type=int, location='args')

    def get(self):
        args = self.book_info_parser.parse_args()
        book_id = args.book_id

        result = base_result.copy()

        book = CheckBookArgs(book_id=book_id, return_book=True).run()

        if type(book) is dict:
            result['error'] = book
            result['msg'] = '书籍不存在'
            return jsonify(result)

        result['data'] = marshal(book, book_detail_info_marshal_with)
        result['success'] = 1
        result['msg'] = '获取书籍信息成功'
        return jsonify(result)


api.add_resource(GetBookInfo, '/get_book_info', endpoint='get_book_info')


# 搜索图书
class SearchBook(Resource):

    search_book_parser = reqparse.RequestParser()
    # 0:标题    1:作者
    search_book_parser.add_argument('search_type', type=int, location='args')
    search_book_parser.add_argument('keywords', type=str, location='args')

    search_book_parser.add_argument('category_id', type=int, location='args')
    search_book_parser.add_argument('author_id', type=int, location='args')
    search_book_parser.add_argument('book_tag_id', type=int, location='args')
    search_book_parser.add_argument('page', type=int, location='args')
    search_book_parser.add_argument('per_page',
                                    type=int,
                                    location='args',
                                    default=20)

    def get(self):
        args = self.search_book_parser.parse_args()
        search_type = args.search_type
        keywords = args.keywords
        category_id = args.category_id
        author_id = args.author_id
        book_tag_id = args.book_tag_id
        page = args.page
        per_page = args.per_page

        result = base_result.copy()

        books = Book.query.filter(
            Book.title.like('%' + keywords +
                            '%')) if search_type == 0 else Book.query.filter(
                                Book.author.name.like('%' + keywords +
                                                      '%')).filter(
                                                          Book.is_del == False)

        if books.all():
            books = books.filter(
                Book.book_category_id == category_id) if category_id else books
            books = books.filter(
                Book.author_id == author_id) if author_id else books
            books = books.filter(Book.book_tags.any(
                BookTag.id == book_tag_id)) if book_tag_id else books

        books = books.paginate(page, per_page, error_out=False)

        result['data'] = {
            'books': marshal(books.items, book_simple_info_marshal_with),
            'has_next': books.has_next,
            'total': books.total,
            'pages': books.pages,
            'current_page': books.page,
        }
        result['success'] = 1
        result['msg'] = '搜索图书成功'
        return jsonify(result)


api.add_resource(SearchBook, '/search_book', endpoint='search_book')


# 获取书籍章节列表
class GetBookChapter(Resource):
    get_book_chapter_parser = reqparse.RequestParser()
    get_book_chapter_parser.add_argument('book_id', type=int, location='args')

    def get(self):
        args = self.get_book_chapter_parser.parse_args()
        book_id = args.book_id

        result = base_result.copy()

        chapters = Chapter.query.filter(Chapter.book_id == book_id,
                                        Chapter.is_del == False).all()
        chapter_list = []
        for chapter in chapters:
            chapter_list.append({
                'chapter_id': chapter.id,
                'title': chapter.title
            })

        result['data'] = chapter_list
        result['success'] = 1
        result['msg'] = '获取书籍章节列表成功'
        return jsonify(result)


api.add_resource(GetBookChapter,
                 '/get_book_chapter',
                 endpoint='get_book_chapter')


# 获取章节内容
class GetChapterContent(Resource):
    get_chapter_content_parser = reqparse.RequestParser()
    get_chapter_content_parser.add_argument('chapter_id',
                                            type=int,
                                            location='args')
    get_chapter_content_parser.add_argument('book_id',
                                            type=int,
                                            location='args')

    def get(self):
        args = self.get_chapter_content_parser.parse_args()
        chapter_id = args.chapter_id
        book_id = args.book_id

        result = base_result.copy()

        prev_chapter_id = None
        next_chapter_id = None
        content = ''

        chapters = Chapter.query.filter(Chapter.book_id == book_id,
                                        Chapter.is_del == False).all()
        if not chapter_id:
            if chapters != []:
                next_chapter_id = chapters[1].id if len(chapters) > 1 else None
                chapter_id = chapters[0].id
                content = chapters[0].content
        else:
            chapter = CheckBookArgs(chapter_id=chapter_id,
                                    return_chapter=True).run()
            if type(chapter) == dict:
                result['errors'] = chapter
                result['msg'] = '获取章节内容失败'
                return jsonify(result)

            positon = chapters.index(chapter)
            prev_chapter_id = chapters[positon - 1].id if positon > 0 else None
            next_chapter_id = chapters[
                positon + 1].id if positon < len(Chapter) - 1 else None
            content = chapter.content

        result['data'] = {
            'content': content,
            'prev_chapter_id': prev_chapter_id,
            'next_chapter_id': next_chapter_id,
            'chapter_id': chapter_id,
            'book_id': book_id
        }
        result['success'] = 1
        result['msg'] = '获取章节内容成功'
        return jsonify(result)


api.add_resource(GetChapterContent,
                 '/get_chapter_content',
                 endpoint='get_chapter_content')
